package com.lefull.lefullbase.utils.helper;


import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.widget.Toast;
import com.lefull.lefullbase.widget.ImageToast;
import com.switfpass.pay.utils.Constants;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class To {
    public static Context mContext;
    /**
     * 之前显示的内容
     */
    private static String oldMsg;
    /**
     * Toast对象
     */
    private static ImageToast toast = null;
    /**
     * 第一次时间
     */
    private static long oneTime = 0;
    /**
     * 第二次时间
     */
    private static long twoTime = 0;

    public static void register(Context context) {
        mContext = context.getApplicationContext();
    }


    private static void check() {
        if (mContext == null) {
            throw new NullPointerException("Must initial call ToastUtils.register(Context context) in your \" +\n" +
                    "                            \"<? \" +\n" +
                    "                            \"extends Application class>");
        }
    }

    public static Context getContext() {
        return mContext;
    }

    public static void show(String msg) {
//        check();
        if (toast == null) {
            toast = new ImageToast(mContext);
            toast.setText(msg);
            toast.show();
            oneTime = System.currentTimeMillis();
        } else {
            twoTime = System.currentTimeMillis();
            if (msg.equals(oldMsg)) {
                if (twoTime - oneTime > Toast.LENGTH_SHORT) {
                    toast.show();
                }
            } else {
                oldMsg = msg;
                toast.setText(msg);
                toast.show();
            }
        }
        oneTime = twoTime;
    }


    public static void showSingle(String msg) {
        if (!StringHelper.isStringNull(msg)) {
            ImageToast toast = ImageToast.getInstance(mContext);
            toast.setText(msg);
            toast.show();
        }
    }

    /**
     * @param context
     * @return 是否安装支付宝
     */
    public static boolean checkAliPayInstalled(Context context) {
        if (context == null) {
            return false;
        }
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }

    public static void openQQ(Context context, String qq) {
        String url = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq;
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, "请安装QQ", Toast.LENGTH_SHORT).show();
        }
    }

    public static void dialPhone(Context context, String phone) {
        try {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, "电话服务不可用", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 控制不可连续点击的时间间隔[  修改控制时间间隔  ]
     */
    public static final int MIN_CLICK_DELAY_TIME = 500;//大时间间隔用于测试
    /**
     * 上一次点击的时间
     */
    private static long lastClickTime = 0;

    public static Boolean normalClick() {
        long currentTime = Calendar.getInstance().getTimeInMillis();
        if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
            lastClickTime = currentTime;
            return true;
        }
        return false;
    }

    public static void dialPhoneHaveTel(Context context, String phone) {
        try {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(phone));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, "电话服务不可用", Toast.LENGTH_SHORT).show();
        }

    }

    public static void sendEMail(Context context, String mailAddr) {
        String[] reciver = new String[]{mailAddr};
        /*
         * String[] mySbuject = new String[] { "test" }; String myCc = "cc";
         * String mybody = "测试Email Intent";
         */
        Intent myIntent = new Intent(Intent.ACTION_SEND);
        myIntent.setType("plain/text");
        myIntent.putExtra(Intent.EXTRA_EMAIL, reciver);
        /*
         * myIntent.putExtra(android.content.Intent.EXTRA_CC, myCc);
         * myIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, mySbuject);
         * myIntent.putExtra(android.content.Intent.EXTRA_TEXT, mybody);
         */
        context.startActivity(Intent.createChooser(myIntent, "发送邮件"));
    }

    private static final char SPACE = 0x20;

    /**
     * 去除字符串中所有空格
     *
     * @param s
     * @return
     */
    public static String removeAllSpace(String s) {
        String endString = "";
        StringBuilder builder = new StringBuilder(endString);
        int len = s.length();
        for (int i = 0; i < len; i++) {
            // 获得字符
            char c = s.charAt(i);
            // 如果该字符不是空格
            if (c != SPACE) {
                builder.append(String.valueOf(c));
            }
        }
        return builder.toString();
    }


    public static String StringFilter(String str) throws PatternSyntaxException {
        String regEx = "[=<>+&\"%^*]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    // 后台
                    return true;
                } else {
                    // 前台
                    return false;
                }
            }
        }
        return false;
    }

    //是否存在sdcard.
    public static boolean isSdcard() {
        try {
            return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @param regex 正则表达式字符串
     * @param str   要匹配的字符串
     * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
     */
    public static boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }

    public static void saveToSdCard(Context context, Bitmap bitmap) {
        // 其次把文件插入到系统图库
        MediaStore.Images.Media.insertImage(context.getContentResolver(),
                bitmap, "title", "description");
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("/sdcard/image.jpg"))));
    }

    //判断是否是手机号码
    public static boolean isMobile(String phone) {

        if (phone != null && phone.length() == 11 && phone.startsWith("1")) {
            return true;
        }
        return false;
    }

    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public static void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            L.debug("catch", "delete file no exists " + file.getAbsolutePath());
        }
    }

    /**
     * 判断字符串中是否包含中文
     * @param str
     * 待校验字符串
     * @return 是否为中文
     * @warn 不能校验是否为中文标点符号
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    public static String[] sortOfString(String[] strings) {
        int len = strings.length;
        for (int i = 0; i <= len - 1; i++) {
            for (int j = i + 1; j <= len - 1; j++) {
                if (compareString(strings[i], strings[j]) < 0) {
                    String temp = strings[j];
                    strings[j] = strings[i];
                    strings[i] = temp;
                }
            }
        }
        return strings;
    }

    /**
     * 比较两个字母大小
     *
     * @param one
     * @param two
     * @return one>two则为正,one==two则为0,one<two则为负
     */
    public static int compareString(String one, String two) {
        // 转换为小写
        one = one.toLowerCase(Locale.getDefault());
        two = two.toLowerCase(Locale.getDefault());
        int oneLen = one.length();
        int twoLen = two.length();
        // 填充至相等位数
        if (oneLen > twoLen) {
            StringBuffer sb = new StringBuffer(two);
            for (int i = 0; i < oneLen - twoLen; i++) {
                sb.append((char) 0);
            }
            two = sb.toString();
        } else if (oneLen < twoLen) {
            StringBuffer sb = new StringBuffer(one);
            for (int i = 0; i < twoLen - oneLen; i++) {
                sb.append((char) 0);
            }
            one = sb.toString();
        }
        // 每一位字符比较
        for (int i = 0; i < one.length() && i < two.length(); i++) {
            char oneChar = one.charAt(i);
            char twoChar = two.charAt(i);
            int diff = (int) oneChar - (int) twoChar;
            if (diff == 0) {
                continue;
            } else {
                return diff;
            }
        }
        return 0;
    }

    public static String getString(byte[] b) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            sb.append(b[i]);
        }
        return sb.toString();
    }

    /**
     * 提交时转换成数组提交
     *
     * @param key
     * @param object
     * @return
     */
    @SuppressWarnings("unused")
    public static String paseData(String key, Object object) {
        StringBuilder sb = new StringBuilder();
        if (object instanceof String || object instanceof Integer
                || object instanceof Boolean) {
            sb.append("&" + key + "=" + toEncodeUtf8(object + ""));
        } else if (object instanceof List) {
            List<Object> list = (List<Object>) object;
            for (int i = 0; i < list.size(); i++) {
                sb.append("&" + paseData(key + "[" + i + "]", list.get(i)));
            }
        } else if (object instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) object;
            for (String mapKey : map.keySet()) {
                if (map.get(mapKey) == null) {
                    continue;
                }
                sb.append("&"
                        + paseData(key + "[" + mapKey + "]", map.get(mapKey)));
            }
        }
        if (sb.length() > 0) {
            return sb.substring(1);
        }
        return "";

    }

    public static String mMd5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(
                    string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * RGB转换为UTF-8
     *
     * @param s
     * @return
     */
    private static String toEncodeUtf8(String s) {
        try {
            return URLEncoder.encode(s, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return s;
    }

    public Bitmap stringtoBitmap(String string) {
        //将字符串转换成Bitmap类型
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    }


